package com.duan.blog.config;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author: duan
 * @description：jwtutil
 * @dateTime: 2021-12-21 17:06
 **/
@Service
public class JWTUtil {
    //过期时间31天
    public static final Long EXPIRE_TIME = 31 * 24 * 3600L * 1000;
    public static final String SECURITY_KEY = "asgd3dsg46!Ms";

    /**
     * 创建token
     * @return          加密token
     */
    public static String createToken(String userName){
        Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        Algorithm algorithm = Algorithm.HMAC512(SECURITY_KEY);
        return JWT.create()
                .withClaim("name", userName)
                .withExpiresAt(date)
                .sign(algorithm);
    }

    /**
     * 验证token
     * @param token     token
     * @param username  用户名
     * @return          boolean
     */
    public static boolean verify(String token, String username) {
        try {
            Algorithm algorithm = Algorithm.HMAC512(SECURITY_KEY);
            JWTVerifier verifier = JWT.require(algorithm)
                    .withClaim("name", username)
                    .build();
            verifier.verify(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 获取jwt中 username
     * @param token     token
     * @return          String
     */
    public static String getUsername(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("name").toString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }
}
